package com.topisv.tms.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.topisv.tms.service.print.impl.*;
import com.topisv.tms.utils.PubUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.service.print.IPrintService;
import com.topisv.tms.service.vo.PrinterStyleType;

/**
 * 打印服务
 * 
 * @authoersion 0.0.16
 */
@Component
public class PrintStyleService {

	@Autowired
	private ExpressStyleService expressStyleService;
	
	
	enum ExpressBeanClass {
		ZTO("ZTO", ZTOPrintServiceImpl.class),
		SF("SF", SFPrintServiceImpl.class),
		YTO("YTO", YTOPrintServiceImpl.class),
		STO("STO", STOPrintServiceImpl.class),
		JD("JD", JDPrintServiceImpl.class),
		TTKDEX("TTKDEX", TTKDEXPrintServiceImpl.class),
		//CAINIAO("CAINIAO",CaiNiaoPrinteServiceImpl.class),
		CAINIAO("CAINIAO", CaiNiaoPrinteServiceNewImpl.class),
		;
		private final String expressName;
		private final Class<?> beanClass;

		private ExpressBeanClass(String expressName, Class<?> beanClass) {
			this.expressName = expressName;
			this.beanClass = beanClass;
		}
		
	}
	
	/**
	 * 获取快递单模板列表
	 * 
	 * @param ordenos 订单号集合
	 * @param expressId 模板ID
	 * @param taskCode 任务编号
	 * @return 打印内容
	 * @throws Exception
	 * 
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getPrintStyleTypes(String ordenos, Long expressId, String taskCode) throws Exception {

		// 判断订单号集合为空
		if (StringUtils.isBlank(ordenos)) {
			throw new RuntimeException("订单号为空!");
		}

		//根据快递模板Id查询
		ExpressStyle expressStyle = expressStyleService.findOne(expressId);
	
		String logisticsCompanyCode = null;
		// 菜鸟
		if ("1".equals(expressStyle.getCainiaoFlg())) {
			logisticsCompanyCode = "CAINIAO";
		} else {//电子面单
			logisticsCompanyCode = expressStyle.getLogisticsCompany().getCompanyCode();
		}
		
		ExpressBeanClass beanClass = ExpressBeanClass.valueOf(logisticsCompanyCode);
		Class<?> clzz = beanClass.beanClass;


		List<PrinterStyleType> printerStyleTypeList = new ArrayList<PrinterStyleType>();
		List<String> orderNoList = Arrays.asList(ordenos.split(":"));
		Object bean = SpringContextUtil.getBeanByClass(clzz);				
		printerStyleTypeList = (List<PrinterStyleType>) ((IPrintService) bean).print(expressId, taskCode, orderNoList);

		Map<String, Object> map = new HashMap<>();

		map.put("expressStyle", expressStyle);
		map.put("printerStyleTypeList", printerStyleTypeList);

		return map;
	}
}
